const qiniu = require("qiniu");
// 你的密钥
const accessKey = 'aY7d0xOKX7vfsXuwSJTsAR9f7AHss-ccHaNcJ-0i'
const secretKey = 'YrriKyqCkCSz1JCLogQnqozWSrDMoTOAd9ydgzFH'
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);


// 创建一个获取token的方法
let uploadToken = function(bucket, uploadUrl) {
    const options = {
        scope: 'qiqi',
        /* 你的七牛仓库 */
        expires: 3600 * 24 * 366, // 过期时间
        returnBody: `{"url":"http://puo95itb9.bkt.clouddn.com/$(key)","code":0}`, // 当七牛请求成功之后 你的返回值
        callbackBodyType: 'application/json'
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(mac);
}

const config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1;
let formUploader = new qiniu.form_up.FormUploader(config);
let putExtra = new qiniu.form_up.PutExtra();


// 后端进行文件上传
function upload(key, localFile, bucket, uploadUrl) {

    return new Promise((resolve, reject) => {
        formUploader.putFile(uploadToken(bucket, uploadUrl), key, localFile, putExtra, function(respErr,
            respBody, respInfo) {
            if (respErr) {
                console.log(respErr);

                reject(respErr);
            }
            if (respInfo.statusCode == 200) {
                resolve(respBody);
            }
        });
    })
}
module.exports = { upload, uploadToken };